package cn.iocoder.yudao.module.esim.util;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.Instant;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;

/**
 * Description:
 * Author: li
 * Date: 2024/3/15
 */
public class ESimUtil {

    public static void main(String[] args) {
        parseDataAndValidity("3GB/30Days");
        parseDataAndValidity("1.2GB/7 days");
        parseDataAndValidity("500MB/1 day");

        System.out.println(convertToBeijingTime("2024-03-01T10:15:49.6538873Z"));
        System.out.println(convertToBeijingTime("0001-01-01T00:00:00"));
    }

    public static int[] parseDataAndValidity(String input) {
        // 定义正则表达式模式
        Pattern pattern = Pattern.compile("(\\d+(?:\\.\\d+)?)\\s*(GB|MB)/(\\d+)\\s*(?:Days|days|day)", Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher(input.trim());

        // 如果匹配到了，提取数据
        if (matcher.find()) {
            final BigDecimal dataAllowance = new BigDecimal(matcher.group(1));
            final String unit = matcher.group(2);
            final int validityPeriodDays = Integer.parseInt(matcher.group(3));

            final int dataAllowanceMb;
            if (unit.equalsIgnoreCase("GB")) {
                // 如果单位是GB，则将GB转换为MB
                dataAllowanceMb = dataAllowance.multiply(new BigDecimal(1024)).setScale(0, RoundingMode.HALF_UP).intValue();
            } else {
                // 如果单位是MB，则直接取整数部分
                dataAllowanceMb = dataAllowance.setScale(0, RoundingMode.HALF_UP).intValue();
            }

            // 输出结果
            return new int[]{dataAllowanceMb, validityPeriodDays};
        } else {
            return new int[]{0, 0};
            //throw new RuntimeException(String.format("数据不符合要求, input = %s", input));
        }
    }

    public static LocalDateTime convertToBeijingTime(String dateString) {
        // 如果是 '0001-01-01T00:00:00'，直接返回 LocalDateTime.MIN
        if (dateString.equals("0001-01-01T00:00:00")) {
            return LocalDateTime.of(1, 1, 1, 0, 0, 0);
        }

        // 解析日期字符串为Instant
        Instant instant = Instant.parse(dateString);

        // 将Instant转换为北京时间的ZonedDateTime
        ZoneId utcZone = ZoneId.of("UTC");
        ZoneId beijingZone = ZoneId.of("Asia/Shanghai");
        ZonedDateTime utcZonedDateTime = instant.atZone(utcZone);
        ZonedDateTime beijingZonedDateTime = utcZonedDateTime.withZoneSameInstant(beijingZone);

        // 北京时间的LocalDateTime
        return beijingZonedDateTime.toLocalDateTime();
    }

}
